/**
 * 主题切换组合式函数
 * 提供主题切换、持久化存储等功能
 */
import { computed, ref } from "vue"
import { ElMessage } from "element-plus"

// 支持的主题列表
export const THEMES = {
  LIGHT: "light",
  DARK: "dark",
};

// 主题配置
export const THEME_CONFIG = {
  [THEMES.LIGHT]: {
    name: "明亮主题",
    icon: "Sunny",
    description: "适合白天使用的明亮主题",
  },
  [THEMES.DARK]: {
    name: "暗色主题",
    icon: "Moon",
    description: "适合夜晚使用的暗色主题",
  },
};

// 存储键名
const THEME_STORAGE_KEY = "judge-platform-theme";

// 全局主题状态
const currentTheme = ref(THEMES.LIGHT);
const isTransitioning = ref(false);

/**
 * 主题切换组合式函数
 */
export const useTheme = () => {
  /**
   * 应用主题到DOM
   */
  const applyTheme = theme => {
    if (!Object.values(THEMES).includes(theme)) {
      console.warn(`Invalid theme: ${theme}`);
      return;
    }

    // 设置过渡状态
    isTransitioning.value = true;

    // 应用主题到根元素
    document.documentElement.setAttribute("data-theme", theme);

    // 更新body类名（兼容某些组件库）
    document.body.className = document.body.className.replace(/theme-\w+/g, "");
    document.body.classList.add(`theme-${theme}`);

    // 更新当前主题
    currentTheme.value = theme;

    // 延迟重置过渡状态
    setTimeout(() => {
      isTransitioning.value = false;
    }, 300);
  };

  /**
   * 切换主题
   */
  const toggleTheme = () => {
    const newTheme = currentTheme.value === THEMES.LIGHT ? THEMES.DARK : THEMES.LIGHT;
    setTheme(newTheme);

    ElMessage.success(`已切换到${THEME_CONFIG[newTheme].name}`);
  };

  /**
   * 设置指定主题
   */
  const setTheme = theme => {
    if (!Object.values(THEMES).includes(theme)) {
      console.warn(`Invalid theme: ${theme}`);
      return;
    }

    applyTheme(theme);

    // 保存到本地存储
    try {
      localStorage.setItem(THEME_STORAGE_KEY, theme);
    } catch (error) {
      console.warn("Failed to save theme to localStorage:", error);
    }
  };

  /**
   * 从本地存储加载主题
   */
  const loadTheme = () => {
    try {
      const savedTheme = localStorage.getItem(THEME_STORAGE_KEY);
      if (savedTheme && Object.values(THEMES).includes(savedTheme)) {
        applyTheme(savedTheme);
        return savedTheme;
      }
    } catch (error) {
      console.warn("Failed to load theme from localStorage:", error);
    }

    // 检测系统主题偏好
    const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
    const systemTheme = prefersDark ? THEMES.DARK : THEMES.LIGHT;

    applyTheme(systemTheme);
    return systemTheme;
  };

  /**
   * 监听系统主题变化
   */
  const watchSystemTheme = () => {
    if (window.matchMedia) {
      const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");

      const handleChange = e => {
        // 只有在没有手动设置主题时才跟随系统
        const savedTheme = localStorage.getItem(THEME_STORAGE_KEY);
        if (!savedTheme) {
          const systemTheme = e.matches ? THEMES.DARK : THEMES.LIGHT;
          applyTheme(systemTheme);
        }
      };

      // 添加监听器
      if (mediaQuery.addEventListener) {
        mediaQuery.addEventListener("change", handleChange);
      } else {
        // 兼容旧版浏览器
        mediaQuery.addListener(handleChange);
      }

      // 返回清理函数
      return () => {
        if (mediaQuery.removeEventListener) {
          mediaQuery.removeEventListener("change", handleChange);
        } else {
          mediaQuery.removeListener(handleChange);
        }
      };
    }
  };

  /**
   * 获取主题配置
   */
  const getThemeConfig = theme => {
    return THEME_CONFIG[theme] || THEME_CONFIG[THEMES.LIGHT];
  };

  /**
   * 获取所有可用主题
   */
  const getAvailableThemes = () => {
    return Object.entries(THEME_CONFIG).map(([key, config]) => ({
      key,
      ...config,
    }));
  };

  // 计算属性
  const isDark = computed(() => currentTheme.value === THEMES.DARK);
  const isLight = computed(() => currentTheme.value === THEMES.LIGHT);
  const themeConfig = computed(() => getThemeConfig(currentTheme.value));
  const nextTheme = computed(() => {
    return currentTheme.value === THEMES.LIGHT ? THEMES.DARK : THEMES.LIGHT;
  });
  const nextThemeConfig = computed(() => getThemeConfig(nextTheme.value));

  return {
    // 状态
    currentTheme: computed(() => currentTheme.value),
    isTransitioning: computed(() => isTransitioning.value),
    isDark,
    isLight,
    themeConfig,
    nextTheme,
    nextThemeConfig,

    // 方法
    toggleTheme,
    setTheme,
    loadTheme,
    watchSystemTheme,
    getThemeConfig,
    getAvailableThemes,

    // 常量
    THEMES,
    THEME_CONFIG,
  };
};

/**
 * 全局主题初始化
 * 在应用启动时调用
 */
export const initTheme = () => {
  const { loadTheme, watchSystemTheme } = useTheme();

  // 加载保存的主题或系统主题
  loadTheme();

  // 监听系统主题变化
  const cleanup = watchSystemTheme();

  // 返回清理函数
  return cleanup;
};

/**
 * 主题切换动画效果
 */
export const useThemeTransition = () => {
  const addTransitionClass = () => {
    document.documentElement.classList.add("theme-transitioning");
  };

  const removeTransitionClass = () => {
    document.documentElement.classList.remove("theme-transitioning");
  };

  const withTransition = async callback => {
    addTransitionClass();

    try {
      await callback();
    } finally {
      setTimeout(removeTransitionClass, 300);
    }
  };

  return {
    addTransitionClass,
    removeTransitionClass,
    withTransition,
  };
};

// 默认导出
export default useTheme;
